package cn.touna.jss.common.spring;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;

import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by Steve.Tao on 2017/7/27.
 */
/*@Component
@Aspect*/
public class ControllerApsect {

    private AtomicLong logIdCounter = new AtomicLong(0);

    @Around("execution(* cn.touna.jss.modules..*.*(..)) && @target(org.springframework.web.bind.annotation.RestController)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        long startTime = System.currentTimeMillis();
        Class cls = pjp.getTarget().getClass();
        long logId = logIdCounter.incrementAndGet();
        String methodName = pjp.getSignature().getName();

        StringBuilder sb = new StringBuilder();
        sb.append("request").append(logId).append(" call ");
        sb.append(cls.getSimpleName()).append(".").append(methodName).append("(");
        for (Object arg : pjp.getArgs()) {
            sb.append(arg).append(",");
        }
        if (sb.charAt(sb.length() - 1) == ',')
            sb.deleteCharAt(sb.length() - 1);
        sb.append(")");

        Logger logger = LogManager.getLogger(cls);
        logger.info(sb);

        sb = new StringBuilder();
        Object result = null;
        try {
            result = pjp.proceed();
        } catch (Throwable e) {
            //记录时间，显示超时的时间间隔是多少
            long cost = System.currentTimeMillis() - startTime;
            sb.append(methodName).append(" request").append(logId).append(" cost ").append(cost).append(" error ");
            sb.append(e);
            logger.error(sb.toString());
            throw e;
        }

        long cost = System.currentTimeMillis() - startTime;
        sb.append(methodName).append("request").append(logId).append(" cost ").append(cost).append(" return ");
        sb.append(result);
        logger.info(sb.toString());
        return result;
    }
}
